
# -*- coding: utf-8 -*-
#   基础配制面板
# @Time    ： 2024/4/12  10:53
# @Auther  ： 徐良
# File     :  baseTableSetPanel.py
from PySide6.QtCore import Qt, Slot
from baseClass.baseQWidget import BaseQWidget
from baseModule.ui.baseTableSetUI import Ui_Form
from share.bioDialog import Infomation
from share.dataFactory import SqlForSave
from share.modelFunction import getTableModelBySql, getFselFIdByModel, getMaxRecrodByModel, checkModelsIsDirty, \
    clearFelByConditionForModel, removeRecordAndReSetFxh, removeRecord
from share.delegateFunction import getConfigDelegate
from share.sqlFunction import getInsertSql, getDelChildSql, getUpdateSqlList, getInsertAndUpdateSqlList, \
    getInsertSqlList, getUpdateSqlListByModelFIdList, getDelParentSqlList
from utils.pcWork import PCWork
import share.globalvar as gol
from PySide6.QtWidgets import QMessageBox, QTableView
from share.baseFunction import quote


class BaseTableSetPanel(BaseQWidget, PCWork, Ui_Form):
    """
    主从表配制面板
    """
    def __init__(self, msDict, parent=None):
        super(BaseTableSetPanel, self).__init__()
        self.queryPanel = None
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.setupUi(self)
        self.parentRow = -1
        self.pFId = -1
        self.toolbarFlag = 'browse'
        self.stackedW = "Yes"
        self.baseDbType = gol.getValue('baseDbType')
        # print(self.baseDbType)
        msDict = eval(msDict)
        print(msDict)
        self.doInitWork(msDict)

        self.readParentData()
        self.readChildData()
        self.parentTableView.clicked.connect(self.onParentTableViewClicked)
        self.saveActionSignal.connect(self.setToolbarSaveButton)
        self.setLbl_info()

    def setLbl_info(self):
        """
        设置父表记录
        :return:
        """
        self.lbl_parent.setText(f"主记录面板，记录数：{self.parentModel.rowCount()}")
        self.lbl_child.setText(f"子表面板，记录数：{self.childModel.rowCount()}")

    def onCheckBoxRow(self, idx):
        """
        勾选事件发生
        :param idx:
        :return:
        """
        self.parentTableView.setCurrentIndex(idx)
        self.onParentTableViewClicked(idx)

    def readParentData(self):
        """
        读父表数据
        :return:
        """
        fieldList = self.getS2_FFieldList().copy()
        fieldList.insert(0, '0 as FSel')

        fieldNameList = self.getS2_FFieldNameList().copy()
        fieldNameList.insert(0, '选择')

        alignList = self.getS2_FAlignList().copy()
        alignList.insert(0, 'center')

        sql = "select {fieldstr} from t_baseConfig order by FNumber".format(fieldstr=','.join(fieldList))

        pdic = {'sql': sql, 'baseDbType': self.baseDbType,
                'fieldNameList': fieldNameList, 'alignList': alignList}

        self.parentModel = getTableModelBySql(pdic)
        self.parentTableView.setModel(self.parentModel)


        width = self.getS2_FWidthList().copy()
        width.insert(0, 45)
        self.parentTableView.setColumnWidthForList(width)
        visible = self.getS2_FVisibleList().copy()
        visible.insert(0, 1)
        self.parentTableView.setHideColumnForCol(visible)

        widgetList = self.getS2_FWidgetList().copy()
        widgetList.insert(0, 'check')
        isEditList = self.getS2_FIsEditList().copy()
        isEditList.insert(0, 0)
        pdic = {'selOption': 0, 'isEditList': isEditList, 'widgetList': widgetList}
        delegate = getConfigDelegate(pdic)
        self.parentTableView.setItemDelegate(delegate)
        self.parentModel.dataChangedSignal.connect(self.onModelDataChanged)
        delegate.checkBoxSignal.connect(self.onCheckBoxRow)

    def readChildData(self, pfid=-1):
        """
        读子表数据
        :return:
        """
        fieldList = self.getS5_FFieldList().copy()
        fieldNameList = self.getS5_FFieldNameList()
        alignList = self.getS5_FAlignList()

        sql = "select {fieldstr} from t_baseConfigEntity where FEntityId={pid} order by FXh". \
            format(fieldstr=','.join(fieldList), pid=str(pfid))

        pdic = {'sql': sql, 'baseDbType': self.baseDbType,
                'fieldNameList': fieldNameList, 'alignList': alignList}

        self.childModel = getTableModelBySql(pdic)
        self.childTableView.setModel(self.childModel)

        width = self.getS5_FWidthList().copy()
        self.childTableView.setColumnWidthForList(width)
        visible = self.getS5_FVisibleList().copy()
        self.childTableView.setHideColumnForCol(visible)

        widgetList = self.getS5_FWidgetList().copy()
        isEditList = self.getS5_FIsEditList().copy()
        pdic = {'selOption': 0, 'isEditList': isEditList, 'widgetList': widgetList}
        delegate = getConfigDelegate(pdic)
        self.childTableView.setItemDelegate(delegate)
        self.childModel.dataChangedSignal.connect(self.onModelDataChanged)

    def actionSelect(self, q):
        sel = q.text()
        if sel == '增加':
            self.parentAdd()
        elif sel == '插入':
            self.parentInsert()
        elif sel == '删除':
            self.parentDel()

    def execChildSql(self, sqlList):
        """
        执行子表的sql语句
        :param sqlList:
        :return:
        """
        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据

            self.readChildData(self.pFId)

            last_index = self.childModel.index(self.childModel.rowCount() - 1, 3)
            self.childTableView.scrollTo(last_index, QTableView.PositionAtBottom)
            self.childTableView.update(last_index)
            modelList = [self.parentModel, self.childModel]
            self.setToolbarSaveButton(checkModelsIsDirty(modelList))  # 设置【保存按钮】

        else:
            Infomation.info(ok['info'])

    def save(self):
        """
        保存单据
        """
        sqlList = []
        pfidList = list(self.parentModel.listUpdate)
        fieldList = self.getS2_FFieldList()
        typeList = self.getS2_FFieldTypeList()
        joinList = self.getS2_FJoinSqlList()

        # 处理主表
        pdic = {'tableName': 't_baseConfig', 'fidList': pfidList, 'model': self.parentModel,
                'fieldList': fieldList, 'typeList': typeList, 'joinList': joinList}

        # 处理新增记录
        newList = []
        if self.parentModel.dirty:
            newList = getInsertSqlList(pdic)
        upList = []
        if len(pfidList) > 0:
            upList = getUpdateSqlListByModelFIdList(pdic)

        sqlList.extend(newList)
        sqlList.extend(upList)

        efidList = list(self.childModel.listUpdate)
        ss = []
        if len(efidList) > 0:
            fieldList = self.getS5_FFieldList()
            typeList = self.getS5_FFieldTypeList()
            joinList = self.getS5_FJoinSqlList()

            pdic = {'tableName': 't_baseConfigEntity', 'fidList': efidList, 'model': self.childModel,
                    'fieldList': fieldList, 'typeList': typeList, 'joinList': joinList}

            ss = getUpdateSqlListByModelFIdList(pdic)

        sqlList.extend(ss)

        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readParentData()
            self.readChildData(self.pFId)

            self.parentModel.listUpdate.clear()
            self.childModel.listUpdate.clear()

            self.parentModel.dirty = False
            self.childModel.dirty = False

            self.setToolbarSaveButton(0)  # 设置【保存按钮】
        else:
            Infomation.info(ok['info'])

    def parentAdd(self):
        """
        父表增加
        :return:
        """

        sql = getInsertSql('t_baseConfig', 'FNumber', quote('00.00'))
        ok = SqlForSave.execSqlList([sql], self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readParentData()
            self.readChildData('-1')
        else:
            Infomation.info(ok['info'])

    def parentInsert(self):
        """
        父表插入
        :return:
        """
        if self.parentRow >= 0:
            self.parentModel.insertRows(self.parentRow, 1)
            icol = self.parentModel.getColForField('fxh')
            index = self.parentModel.index(self.parentRow, icol)
            self.parentModel.setData(index, 1)
        else:
            Infomation.info('请选择行')
            return

    def parentDel(self):
        """
        父表删除
        :return:
        """

        # 获取父表Fid
        fid, rec = getFselFIdByModel(self.parentModel)
        if fid == '-1':
            Infomation.info('请勾选主表记录')
            return

        # 检查当前的fid是否为空，是，则为新增记录，只需在model中删除
        xFid = self.parentModel.record(rec).value('FId')
        if xFid == '':
            removeRecord(self.parentModel, rec)
            return

        # 判断是否需要先保存
        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return

        fnumber = self.parentModel.record(rec).value('FNumber')
        fname = self.parentModel.record(rec).value('FName')
        ask = Infomation.question(f"删除行号 {rec + 1}, 编码为 {fnumber}, 名称为{fname}的记录？")
        if ask == QMessageBox.No:
            return

        sqlList = getDelParentSqlList('t_baseConfig', fid, ['t_baseConfigEntity'])
        # 移除model中指定记录
        removeRecord(self.parentModel, rec)

        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readParentData()
            self.readChildData('-1')
            self.setToolbarSaveButton(0)
        else:
            Infomation.info(ok['info'])

    @Slot()
    def on_btn_addChild_clicked(self):
        """
        编辑格式增加
        :return:
        """
        # 获取父表Fid
        self.pFId, rec = getFselFIdByModel(self.parentModel)
        if self.pFId == '':
            Infomation.info('请先保存主表记录')
            return
        if self.pFId == '-1':
            Infomation.info('请勾选主表记录')
            return

        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return

        fxh = str(getMaxRecrodByModel(self.childModel) + 1)
        sql = getInsertSql('t_baseConfigEntity', 'FEntityId, FXh', self.pFId + ',' + fxh)

        self.execChildSql([sql])

    @Slot()
    def on_btn_insertChild_clicked(self):
        """
        编辑格式插入
        :return:
        """
        # 获取父表Fid
        self.pFId, pRow = getFselFIdByModel(self.parentModel)
        if self.pFId == '-1':
            Infomation.info('请勾选主表记录')
            return

        if self.pFId == '':
            Infomation.info('请先保存主表记录')
            return

        index = self.childTableView.currentIndex()
        if index.isValid():
            row = index.row()

            col = self.childModel.getColForField('fxh')

            self.childModel.insertRows(row, 1)
            idx = self.childModel.index(row, col)
            ifxh = row + 1
            self.childModel.setData(idx, ifxh)

            # 加上父ID
            pcol = self.childModel.getColForField('fentityid')
            pidx = self.childModel.index(row, pcol)
            self.childModel.setData(pidx, self.pFId)

            end = self.childModel.rowCount()
            row = row + 1
            ifxh += 1
            for irow in range(row, end):
                idx = self.childModel.index(irow, col)
                self.childModel.setData(idx, irow + 1)


            fieldList = self.getS5_FFieldList()
            typeList = self.getS5_FFieldTypeList()
            joinList = self.getS5_FJoinSqlList()
            pdic = {'tableName': 't_baseConfigEntity', 'model': self.childModel,
                    'fieldList': fieldList, 'typeList': typeList, 'joinList': joinList}

            sqlList = getInsertAndUpdateSqlList(pdic)

            ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
            if ok['ret']:
                # 重读数据
                self.readChildData(self.pFId)
                self.childModel.listUpdate.clear()
                self.childModel.dirty = False
                modelList = [self.parentModel, self.childModel]
                self.setToolbarSaveButton(checkModelsIsDirty(modelList))  # 设置【保存按钮】
            else:
                Infomation.info(ok['info'])
        else:
            Infomation.info('请选择子表的指定行')

    @Slot()
    def on_btn_delChild_clicked(self):
        """
        表格格式增加
        :return:
        """
        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return

        index = self.childTableView.currentIndex()
        if index.isValid():
            row = index.row()
            ask = Infomation.question(f"字段面板， 删除序号 {self.childModel.record(row).value('FXh')}, 字段名为"
                                      f" {self.childModel.record(row).value('FField')} 的记录？")

            if ask == QMessageBox.Yes:
                sqlList = []
                fid = self.childModel.record(row).value('FId')
                sql = getDelChildSql('t_baseConfigEntity', str(fid))
                sqlList.append(sql)

                pFid = self.childModel.record(row).value('FEntityId')
                # 处理model, 处理序号
                removeRecordAndReSetFxh(self.childModel, row)

                fieldList = self.getS5_FFieldList()
                typeList = self.getS5_FFieldTypeList()
                joinSqlList = self.getS5_FJoinSqlList()
                ssList = getUpdateSqlList('t_baseConfigEntity', self.childModel, fieldList, typeList, joinSqlList)
                sqlList.extend(ssList)

                self.execChildSql(sqlList)

            else:
                return
        else:
            Infomation.info('请选定要删除的字段表行')

    def onParentTableViewClicked(self, index):
        """

        :param index:
        :return:
        """

        if index.isValid():

            self.parentRow = index.row()
            clearFelByConditionForModel(self.parentModel, self.parentRow)
            self.pFId = self.parentModel.record(self.parentRow).value('FId')
            if self.pFId == '':
                return
            self.readChildData(self.pFId)
            # 设置当前单元格为可编辑状态
            # 先断开数据变化的信号
            self.parentModel.dataChangedSignal.disconnect(self.onModelDataChanged)
            self.parentTableView.edit(index)  # idx是当前选中的索引 否则会不进入编辑状态
            # 再连接信号
            self.parentModel.dataChangedSignal.connect(self.onModelDataChanged)
            self.setLbl_info()

            # 设置下一个单元格的索引
            next_index = self.parentTableView.model().index(index.row(), index.column())
            if next_index.isValid():
                self.parentTableView.setCurrentIndex(next_index)



if __name__ == '__main__':
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    dic = "{'msFNumber': '70.06', 'msClass': '11', 'msSaveType':1}"
    window = BaseTableSetPanel(dic)
    window.show()
    sys.exit(app.exec())